/**
 * @author yxw
 * date : 2013年10月5日 下午12:32:09 
 */
package com.tzinfo.tzt.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.util.GPSThread;
import com.tzinfo.tzt.activity.util.MyApplication;
import com.tzinfo.tzt.config.AppDataConfig;
import com.tzinfo.tzt.config.FilterConfig;
import com.tzinfo.tzt.domain.LocationGeocoder;
import com.tzinfo.tzt.util.HttpTools;
import com.tzinfo.tzt.util.JsonTools;

public class SelectCityActivity extends BaseActivity implements
		OnItemClickListener {

	private ListView cityList;
	private SimpleAdapter simpleAdapter;
	private List<Map<String, Object>> data;
	protected LocationGeocoder geocoder;
	private Location location = MyApplication.location;
	private TextView locationText;
	private LinearLayout gspLayout;
	protected int locationCode = 0;
	private LocationManager loctionManager;
	private String contextService = Context.LOCATION_SERVICE;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_select_city);
		init();
	}

	private void init() {
		locationText = (TextView) this.findViewById(R.id.text_gps_city_name);
		gspLayout = (LinearLayout) this.findViewById(R.id.layout_under_top);
		cityList = (ListView) this.findViewById(R.id.listview_citys);
		getData();
		simpleAdapter = new SimpleAdapter(this, data,
				R.layout.item_select_city, new String[] { "name" },
				new int[] { R.id.text_citys_name });
		cityList.setAdapter(simpleAdapter);
		cityList.setOnItemClickListener(this);
		mProgressBar = (ProgressBar)findViewById(R.id.progressbar_loding);

		if (location == null) {
			if (!GPSThread.getInstance(this).getLocation()) {
				locationText.setText("无法获取当前位置!");
				gspLayout.setOnClickListener(null);
			} else {
				showProgressBar();
				new Thread(getLocationAddressRun).start();
			}
		} else {
			showProgressBar();
			new Thread(getLocationAddressRun).start();
		}

	}


	private void getData() {
		data = new ArrayList<Map<String, Object>>();
		Map<String, Object> map;
		for (int i = 0; i < FilterConfig.FILTER_CONTENT[0].length; i++) {
			map = new HashMap<String, Object>();
			map.put("name", FilterConfig.FILTER_CONTENT[0][i]);
			data.add(map);
		}
	}

	// 不使用监听是因为在布局文件中已经定义
	public void back(View view) {
		if (MyApplication.locationCode == -1) {
			MyApplication.locationCode = 0;
			Intent intent = new Intent();
			intent.putExtra("locationCode", 0);
			sharedPreferences.saveMessage("locationCode", "0");
			setResult(2, intent);
		}
		this.finish();
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case 1:
				// if (geocoder.getCityCode() == 244) {
				locationCode = 0;
				locationText.setText(geocoder.getDistrict());
				while (locationCode < FilterConfig.FILTER_CONTENT[0].length
						&& !geocoder.getDistrict().equals(
								FilterConfig.FILTER_CONTENT[0][locationCode])) {
					locationCode++;
				}
				if (locationCode == FilterConfig.FILTER_CONTENT[0].length) {
					locationText.setText(geocoder.getDistrict() + "，您不在指定地区，默认"
							+ FilterConfig.FILTER_CONTENT[0][0]);
					MyApplication.nowLocationCode=locationCode-1;
					locationCode = 0;
				}else{
					MyApplication.nowLocationCode=locationCode;
				}
				gspLayout.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						MyApplication.locationCode = locationCode;
						Intent intent = new Intent();
						intent.putExtra("locationCode", locationCode);
						sharedPreferences.saveMessage("locationCode",
								locationCode + "");
						setResult(2, intent);
						excFinish();
					}
				});

				// } else {
				// locationText.setText("您不在台州地区!");
				// locationText.setOnClickListener(null);
				// }

				removeProgressBar();
				break;
			case -1:
				getDataError((String) msg.obj);
				break;
			case 3:
				// 已经是最后一页
				break;
			case 7:
				break;
			case 0:
				break;
			}
		}
	};

	private void getDataError(String ERRORMESSAGE) {
		new AlertDialog.Builder(this).setCancelable(false)
				.setMessage(ERRORMESSAGE)
				.setPositiveButton(getResources().getString

				(R.string.cancel), new DialogInterface.OnClickListener()

				{
					public void onClick

					(DialogInterface dialog, int which) {
						finish();
					}
				}).setNegativeButton(getResources().getString

				(R.string.try_again), new DialogInterface.OnClickListener()

				{
					public void onClick(

					DialogInterface dialogInterface, int

					whichButton) {
						showProgressBar();
						new Thread(getLocationAddressRun).start();
					}
				}).show();
	}

	/**
	 * 线程 得地理位置
	 */
	Runnable getLocationAddressRun = new Runnable() {

		@Override
		public void run() {
			Message msg = handler.obtainMessage();
			String jsonString;
			String url=AppDataConfig.baiduGeoUrl + "?ak=" + AppDataConfig.baiduak
					+ "&callback=renderReverse&" + "location="
					+ location.getLatitude() + ","
					+ location.getLongitude() + "&output=json&pois=0";
			Log.e("baidu",url);
			jsonString = HttpTools.getJsonContent(url);
			Log.e("JsonString gb2312", jsonString);
			geocoder = JsonTools.getLocationToAddress(jsonString);
			if (geocoder.getStatus() == 0) {
				msg.arg1 = 1;
			} else {
				msg.arg1 = -1;
				msg.obj = geocoder.getErrorMessage();
			}
			handler.sendMessage(msg);
		}
	};

	@Override
	public void onItemClick(AdapterView<?> adapterview, View view, int i, long l) {
		MyApplication.locationCode = i;
		Intent intent = new Intent();
		intent.putExtra("locationCode", i);
		sharedPreferences.saveMessage("locationCode", i + "");
		setResult(2, intent);
		this.finish();
	}

	protected void excFinish() {
		this.finish();
	}

}
